﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Help;
using Model;

namespace BLLA
{
    public partial class Order_Shelves_T : BaseBLL<Model.Order_Shelves_T>, IBLL.IOrder_Shelves_TBLL
    {
        ObjectSerialize os = new ObjectSerialize();
        DataResult result = new DataResult();

        /// <summary>
        /// 设置商品上架数量
        /// </summary>
        /// <param name="DishesID">菜品ID</param>
        /// <param name="HasNub">数量</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式(1:json;2:xml)</param>
        /// <returns></returns>
        public string SetOrder_Shel(string DishesID, int HasNub, string YZM, int RETID)
        {
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            #region 业务层
            try
            {
                string time = DateTime.Now.ToString("HHmm");
                int day = int.Parse(DateTime.Now.ToString("yyyyMMdd"));
                string merid = base.DBSession.IOrder_Dishes_TDAL.GetListBy(u => u.DishesID == DishesID).First().MerID;
                List<Model.Order_Shelves_T> ShelList = base.DBSession.IOrder_Shelves_TDAL.GetListBy("SELECT * FROM Order_Shelves_T where SheDateB<=" + day + " and SheDateE>=" + day + " and MerID='" + merid + "' and  SheTimeB<'" + time + "' and SheTimeE > '" + time + "' and SheState=1");

                if (ShelList.Count != 0)
                {
                    int sid = ShelList[0].SheID;
                    List<Model.Order_Sales_T> sal = base.DBSession.IOrder_Sales_TDAL.GetListBy(u => u.SheID == sid & u.DishesID == DishesID & u.SalesDate == day);
                    if (sal.Count > 0)
                    {
                        Model.Order_Sales_T s = sal[0];
                        if (HasNub <= s.SalesNub & HasNub >= 0)
                        {
                            s.HaveNub = HasNub;

                            if (base.DBSession.IOrder_Sales_TDAL.Modify(s) > 0)
                            {
                                result.BS = "1";
                                result.Msg = "更新成功！";
                            }
                            else
                            {
                                result.BS = "-1";
                                result.Msg = "更新失败！";
                            }
                        }
                        else
                        {
                            result.BS = "-1";
                            result.Msg = "数量超出规定范围！";
                        }
                    }
                    else
                    {
                        result.BS = "-1";
                        result.Msg = "查询不到数据！";
                    }
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "查询不到数据！";
                }
            }
            catch (Exception)
            {
                result.BS = "-1";
                result.Msg = "更新失败！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            return os.StringOfObject(result, RETID);
        }
        /// <summary>
        /// 更新商品上架信息
        /// </summary>
        /// <param name="OperID">操作员ID</param>
        /// <param name="json">更新信息</param>
        /// <param name="tag">操作标签（1：新增；2：修改；3：删除）</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1：JSON；2：XML）</param>
        /// <returns></returns>
        public string SetOrder_Shelves(int OperID, string json, int tag, string YZM, int RETID)
        {
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            #region 执行操作
            try
            {
                Model.Order_Shelves_T info = ParseClass<Model.Order_Shelves_T>.StrDeserialize(json, RETID);
                WriteLog.WriteW("OperID:" + OperID+" json:"+json+" tag:"+tag);
                string T = "";
                int ret = -1;
                // 根据操作标签Tag判断是什么操作
                switch (tag)
                {
                    case 1:
                        T = "新增";
                        List<Model.Order_Shelves_T> list = base.GetListBy(u => u.MerID == info.MerID & u.SheState == 1);
                        foreach (Model.Order_Shelves_T item in list)
                        {
                            if ((item.SheDateB <= info.SheDateB & item.SheDateE >= info.SheDateB) | (item.SheDateB >= info.SheDateB & item.SheDateB <= info.SheDateE))
                            {
                                if ((int.Parse(item.SheTimeB) <= int.Parse(info.SheTimeB) & int.Parse(item.SheTimeE) >= int.Parse(info.SheTimeB)) | (int.Parse(item.SheTimeB) >= int.Parse(info.SheTimeB) & int.Parse(item.SheTimeB) <= int.Parse(info.SheTimeE)))
                                {
                                    result.BS = "-3";
                                    result.Msg = "日期有冲突，不能新增！";
                                    return os.StringOfObject(result, RETID);
                                }
                            }
                        }
                        info.SheID = Int32.Parse(GetSysKey.GetKey("SheKey"));
                        info.SheState = 1;
                        ret = base.Add(info);
                        break;

                    case 2:
                        T = "修改";
                        list = base.GetListBy(u => u.MerID == info.MerID & u.SheState == 1 & u.SheID != info.SheID); 
                        foreach (Model.Order_Shelves_T item in list)
                        {
                            //   if ((item.SheDateB <= info.SheDateB & item.SheDateE <= info.SheDateB) | (item.SheDateB <= info.SheDateE & item.SheDateE <= info.SheDateE))
                            if ((item.SheDateB <= info.SheDateB & item.SheDateE >= info.SheDateB) | (item.SheDateB >= info.SheDateB & item.SheDateB <= info.SheDateE))
                            {
                                if ((int.Parse(item.SheTimeB) <= int.Parse(info.SheTimeB) & int.Parse(item.SheTimeE) >= int.Parse(info.SheTimeB)) | (int.Parse(item.SheTimeB) >= int.Parse(info.SheTimeB) & int.Parse(item.SheTimeB) <= int.Parse(info.SheTimeE)))
                                {
                                    result.BS = "-3";
                                    result.Msg = "日期有冲突，不能修改！";
                                    return os.StringOfObject(result, RETID);
                                }
                            }
                        }

                        info.SheState = 1;
                        Model.Order_Shelves_T tmp = base.GetListBy(u => u.SheID == info.SheID).First();
                        if (tmp.DishesNub != info.DishesNub)
                        {
                            string time = DateTime.Now.ToString("yyyyMMdd");
                            int day = int.Parse(time.Substring(0, 8));
                            int ti = Convert.ToInt32(time);
                            if (info.SheDateB <= ti & ti <= info.SheDateE)
                            {
                                List<Model.Order_Sales_T> SaleList = base.DBSession.IOrder_Sales_TDAL.GetListBy(u => u.SalesDate == day & u.SheID == info.SheID & u.SheState == 1);
                                if (SaleList.Count > 0)
                                {
                                    List<string> inf = info.DishesID.Split(',').ToList();//参数的DishesID
                                    List<string> tm = tmp.DishesID.Split(',').ToList();//数据库的DishesID
                                    List<string> infnum = info.DishesNub.Split(',').ToList();
                                    List<string> tmnum = tmp.DishesNub.Split(',').ToList();
                                    List<string> duo = (from m in inf where !tm.Contains(m) select m).ToList();
                                    List<string> sao = (from m in tm where !inf.Contains(m) select m).ToList();
                                    foreach (var item in sao)
                                    {
                                        Model.Order_Sales_T m = (from a in SaleList where a.DishesID == item select a).ToList().First();
                                        base.DBSession.IOrder_Sales_TDAL.Del(m);
                                    }
                                    List<Model.Order_Sales_T> SaleLi = new List<Model.Order_Sales_T>();
                                    foreach (var item in duo)
                                    {
                                        Model.Order_Sales_T Sale = new Model.Order_Sales_T();
                                        Sale.SheID = info.SheID;
                                        Sale.DishesID = item;
                                        Sale.SalesNub = int.Parse(infnum[inf.IndexOf(item)]);
                                        Sale.HaveNub = Sale.SalesNub;
                                        Sale.IntTime = time;
                                        Sale.SalesDate = day;
                                        Sale.SheState = 1;
                                        Sale.BZ = "";
                                        SaleLi.Add(Sale);
                                    }
                                    base.DBSession.IOrder_Sales_TDAL.Add(SaleLi);
                                    List<string> orgl = (from m in inf where tm.Contains(m) select m).ToList();
                                    foreach (var item in orgl)
                                    { 
                                        if (infnum[inf.IndexOf(item)] != tmnum[tm.IndexOf(item)])
                                        {
                                            Model.Order_Sales_T m = (from a in SaleList where a.DishesID == item select a).ToList().First();
                                          
                                            //新剩余= 新上架-(旧上架-剩余)
                                            m.HaveNub=int.Parse(infnum[inf.IndexOf(item)])-(m.SalesNub-m.HaveNub);
                                            if (m.HaveNub < 0)
                                            {
                                                m.HaveNub = 0;
                                            }

                                            m.SalesNub = int.Parse(infnum[inf.IndexOf(item)]);
                        
                                            base.DBSession.IOrder_Sales_TDAL.Modify(m);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                result.BS = "-1";
                                result.Msg = "商品已下架";
                                return os.StringOfObject(result, RETID);
                            }
                        }
                        Help.FuZhi<Model.Order_Shelves_T>.FZ(ref tmp, info);
                        ret = base.Modify(tmp);
                        break;
                    case 3:
                        T = "删除";
                        List<Model.Order_Shelves_T> list_tmp = base.GetListBy(u => u.SheID == info.SheID);
                        if (list_tmp != null && list_tmp.Count > 0)
                        {
                            tmp = list_tmp.First();
                            tmp.SheState = 0;
                            ret = base.Modify(tmp);
                        }

                        break;
                }

                if (ret > 0)
                {
                    // 将操作记录到日志表中
                    Model.Order_OperationFlow_T Log = new Model.Order_OperationFlow_T();
                    Log.OperationTitle = "更新商品上架信息";
                    Log.OperationText = T + "商品上架信息成功";
                    Log.OperationType = "1F0006";
                    Log.OperationRes = "成功";
                    Log.OperationUser = OperID;
                    string str_log = os.StringOfObject(Log, RETID);
                    bool isSuccess = new Order_OperationFlow_T().AddOrder_OperationFlow(str_log, RETID);
                    if (!isSuccess)
                    {
                        WriteLog.WriteW("新增系统操作流水失败");
                    }
                    result.BS = "1";
                    result.Msg = "更新成功";
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "更新失败";
                }
            }
            catch (Exception ex)
            {
                WriteLog.WriteW("更新商品上架信息失败：" + ex.Message);
                result.BS = "-1";
                result.Msg = "更新失败";
            }
            #endregion
            return os.StringOfObject(result, RETID);
        }
    }
}
